import gnotifier_module
import gnotifier, pygtk, os, sys, gtk, gobject, webbrowser, re, httplib, xml.dom.minidom, time
APP_DIR = gnotifier.APP_DIR

class GCalendarNotifier(gnotifier_module.GNmodule):
    icon = None
    lastCheck = None
    statusicon = 'calendar.gif'
    service = 'cl'
    feedUri = 'https://www.google.com/calendar/feeds/default/private/full?futureevents=true'

    def delete_event(self, widget, event, data=None):
        # If you return FALSE in the "delete_event" signal handler,
        # GTK will emit the "destroy" signal. Returning TRUE means
        # you don't want the window to be destroyed.
        # This is useful for popping up 'are you sure you want to quit?'
        # type dialogs.
        print "delete event occurred"

        # Change FALSE to TRUE and the main window will not be destroyed
        # with a "delete_event".
        return False

    def destroy(self, widget, data=None):
        print "Bye!"
        gtk.main_quit()
          
        
    def _checkNewMail(self):
        i = 0
        fullCount = 0
        data_array = []      
        defaultReminder = 10
        checkEvery = 2*24*60
        alertList = []
        reminder_str = defaultReminder

        if (self.lastCheck == None):
            self.lastCheck = time.time()
        doc=xml.dom.minidom.parseString(self.gmailFeed.feed)

        for entry in doc.getElementsByTagName("entry"):
            for author in entry.getElementsByTagName("author"):
                for name in author.getElementsByTagName("name"):                
                    name_str = name.firstChild.nodeValue
            for title in entry.getElementsByTagName("title"):
                title_str = title.firstChild.nodeValue
            for link in entry.getElementsByTagName("link"):
                link_str = link.getAttribute("href")
            for reminder in entry.getElementsByTagName("gd:reminder"):
                try:                
                    reminder_str = reminder.getAttribute("minutes")
                except:
                    try:
                        reminder_str = reminder.getAttribute("hours")/60
                    except:
                        try:
                            reminder_str = reminder.getAttribute("days")/60*24
                        except:
                            reminder_str = defaultReminder
            
            print 'Remind me in '+str(reminder_str)+' minutes...'
            for when in entry.getElementsByTagName("gd:when"):
                starttime_str = when.getAttribute("startTime")
                endtime_str = when.getAttribute("endTime")
            isOneDay, timetuple = self.__parseDate(starttime_str)

            if ((time.mktime(timetuple) < time.time() + int(reminder_str)*60)):
                self.alert(title_str)
            elif (time.mktime(timetuple) - int(reminder_str)*60 < time.time() + checkEvery*60):
                print 'Setting alert for '+title_str+'... '
                print (time.mktime(timetuple) - int(reminder_str)*60 - time.time())*1000
                alertList.append(gobject.timeout_add(int(time.mktime(timetuple) - int(reminder_str)*60 - time.time())*1000, self.alert, title_str))
            
            wday_str = time.strftime('%a', timetuple)
            time_str = time.strftime('%H:%M:%S', timetuple)
            month_str = time.strftime('%b %d', timetuple)

            i = i + 1

          
        self.lastCheck = time.time()#time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())      

        return i    

    def alert(self, text):
        data_array = []
        data_array.append({'title':text})
        #main.pluginManager.executePluginAction('newEventReminder', [data_array])
        self.pluginManager.executePluginAction('newEventReminder', [data_array])
        print text+' Event!'
        return False

    def _generateMenu(self):
        print "generateMenu..."
        self.menu = gtk.Menu()

        self.labelItemRead = gtk.Label('No Upcoming Events')        
        self.menuItemRead = gtk.MenuItem()
        self.menuItemRead.add(self.labelItemRead)
        self.menu.append(self.menuItemRead)

        self.menuItemsCheckNow = gtk.MenuItem('Check Now')
        self.menuItemsCheckNow.connect("activate", self.getMail)
        self.menu.append(self.menuItemsCheckNow)

        self.separator = gtk.SeparatorMenuItem()
        self.menu.append(self.separator)

        self.menuCompose = gtk.MenuItem('Create Event')
        self.menuCompose.connect("activate", lambda w: webbrowser.open('http://www.google.com/calendar/event?action=TEMPLATE&auth='+self.gmailFeed.token))
        self.menu.append(self.menuCompose)

        self.separator = gtk.SeparatorMenuItem()
        self.menu.append(self.separator)

        self.menuPreferences = gtk.MenuItem('Preferences...')
        self.menuPreferences.connect("activate", lambda w: self.loginInto())
        self.menu.append(self.menuPreferences)

        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        self.menuItem.connect("activate", lambda w: self.showPopup)
        self.menu.append(self.menuItem)

        self.separator = gtk.SeparatorMenuItem()
        self.menu.append(self.separator)

        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        self.menuItem.connect("activate", self.destroy, self.icon)
        self.menu.append(self.menuItem) 

    def _populateMenu(self):
        i = 0;
        print "Populate menu..."
        #print self.gmailFeed.feed
        self.menuReadItems = gtk.Menu()

        doc=xml.dom.minidom.parseString(self.gmailFeed.feed)
        #doc =xml.dom.minidom.parseString('<a></a>')
        for entry in doc.getElementsByTagName("entry"):
            for when in entry.getElementsByTagName("gd:when"):
                starttime_str = when.getAttribute("startTime")
                endtime_str = when.getAttribute("endTime")

            isOneDay, timetuple = self.__parseDate(starttime_str)
            wday_str = time.strftime('%a', timetuple)
            time_str = time.strftime('%H:%M:%S', timetuple)
            month_str = time.strftime('%b %d', timetuple)
            i = i + 1
            for author in entry.getElementsByTagName("author"):
                for name in author.getElementsByTagName("name"):                
                    name_str = name.firstChild.nodeValue
            for title in entry.getElementsByTagName("title"):
                title_str = title.firstChild.nodeValue
            for link in entry.getElementsByTagName("link"):
                link_str = link.getAttribute("href")

            
            if (isOneDay):
                self.menuItem = gtk.MenuItem(wday_str +' '+ month_str +' | '+ title_str, False)
            else:
                self.menuItem = gtk.MenuItem(wday_str +' '+ time_str +' | '+ title_str, False)

            self.menuItem.connect("activate", self.openUrl, link_str+'&auth='+self.gmailFeed.token)
            self.menuReadItems.append(self.menuItem)
    
        if (i > 0):        
            self.menuItemRead.set_submenu(self.menuReadItems)
            self.labelItemRead.set_label('%i Upcoming Events' % i)
            self.menu.show()
        elif (i == 0):
           self.labelItemRead.set_label('No Upcoming Events')
           self.menuItemRead.remove_submenu()

    def __parseDate(self, dateStr):
        try:
            # If it's a one day date
            isOneDay = True
            timetuple = time.strptime(dateStr, "%Y-%m-%d");                          
        except Exception, e:
            try:            
                isOneDay = False
                timetuple = time.strptime(dateStr[:len(dateStr)-10], "%Y-%m-%dT%H:%M:%S") 
            except Exception, e:
                raise
        return isOneDay, timetuple

